#include "filesys/inode.h"
#include <list.h>
#include <debug.h>
#include <round.h>
#include <string.h>
#include "filesys/filesys.h"
#include "filesys/free-map.h"
#include "threads/malloc.h"
#include "filesys/cache.h"
#include "threads/thread.h"

/* Identifies an inode. */
#define INODE_MAGIC 0x494e4f44
#define DIRECT_CNT 10
#define DOUBLE_INDIRECT_CNT (DIRECT_CNT + BLOCK_SECTOR_SIZE/4)
#define DIRECT_LENGTH (DIRECT_CNT * BLOCK_SECTOR_SIZE)
#define FIRST_INDIRECT_LENGTH ((DIRECT_CNT + BLOCK_SECTOR_SIZE / 4) * BLOCK_SECTOR_SIZE)

//ht
//大小为一个扇区的结构体，用来储存间接索引扇区块
//间接索引扇区块包括了128个扇区号，用来索引其他扇区
struct inode_indirect
{
    block_sector_t entry[128];
};

/* On-disk inode.
   Must be exactly BLOCK_SECTOR_SIZE bytes long. */
//将inode_disk结构体修改，舍去原来的start
//对于索引我们采用了经典的10个直接索引+1个一级间接索引+1个二级间接索引
//这样一个文件最大支持长度为 (10+128+128*128)*512
//改的时候要注意对齐512大小
struct inode_disk
  {
    block_sector_t start;               /* First data sector. 舍去不用*/
    block_sector_t direct[DIRECT_CNT];  //直接索引
    block_sector_t indirect1;           //一级间接索引
    block_sector_t indirect2;           //二级间接索引
    off_t length;                       /* File size in bytes. */
    unsigned magic;                     /* Magic number. */

    uint32_t depth;  //无用

//    uint32_t dir;

    uint32_t unused[122 - DIRECT_CNT];  /* Not used. */
  };

/* Returns the number of sectors to allocate for an inode SIZE
   bytes long. */
static inline size_t
bytes_to_sectors (off_t size)
{
  return DIV_ROUND_UP (size, BLOCK_SECTOR_SIZE);
}

/* In-memory inode. */
struct inode 
  {
    struct list_elem elem;              /* Element in inode list. */
    block_sector_t sector;              /* Sector number of disk location. */
    int open_cnt;                       /* Number of openers. */
    bool removed;                       /* True if deleted, false otherwise. */
    int deny_write_cnt;                 /* 0: writes ok, >0: deny writes. */
    struct inode_disk data;             /* Inode content. */
  };

/* Returns the block device sector that contains byte offset POS
   within INODE.
   Returns -1 if INODE does not contain data for a byte at offset
   POS. */
static block_sector_t
byte_to_sector (const struct inode *inode, off_t pos) 
{
  ASSERT (inode != NULL);
  if (pos < inode->data.length)
  {
    return inode->data.start + pos / BLOCK_SECTOR_SIZE;
  }
  else
    return -1;
}

//ht
//新版byte_to_sector函数，舍弃旧函数改用新的
//通过位移来寻找位于哪个扇区
static block_sector_t
byte_to_sector_index (const struct inode *inode, off_t pos)
{
    ASSERT(inode != NULL);
    if (pos <= inode->data.length)
    {
        block_sector_t tmp;
        size_t sectors = pos / 512;

//        if(sectors == 0)
//            return inode->data.direct[0];

        //分开情况寻找
        //在二级间接区寻找
        if(sectors >= DOUBLE_INDIRECT_CNT)
        {
            sectors -= DOUBLE_INDIRECT_CNT;
            size_t fst_num = (sectors) / 128 ;
            size_t scd_num = sectors - fst_num*128;
            struct inode_indirect *fst = calloc(1,sizeof *fst);
            struct inode_indirect *scd = calloc(1,sizeof *scd);
            read_from_cache(fs_device,inode->data.indirect2,0,BLOCK_SECTOR_SIZE,fst);
            read_from_cache(fs_device,fst->entry[fst_num],0,BLOCK_SECTOR_SIZE,scd);
            tmp = scd->entry[scd_num];
            free(scd);
            free(fst);
        }//在一级间接区寻找
        else if(sectors >=DIRECT_CNT && sectors <DOUBLE_INDIRECT_CNT)
        {
            sectors -= DIRECT_CNT;
            size_t fst_num = sectors;
            struct inode_indirect *fst = calloc(1,sizeof *fst);
            read_from_cache(fs_device,inode->data.indirect1,0,BLOCK_SECTOR_SIZE,fst);
            tmp = fst->entry[fst_num];
//            printf("-------------------------------------------------------------------------------------------------------------------找到了扇区%d\n",fst->entry[fst_num]);
            free(fst);
        }//在直接区寻找
        else
        {
            tmp = inode->data.direct[sectors];
        }
//        printf("位于%d的inode通过位移%d找到了%d扇区\n",inode->sector,pos,tmp);
        return tmp;
    }
    else
        return -1;
}

/* List of open inodes, so that opening a single inode twice
   returns the same `struct inode'. */
static struct list open_inodes;

/* Initializes the inode module. */
void
inode_init (void) 
{
  list_init (&open_inodes);
}

/* Initializes an inode with LENGTH bytes of data and
   writes the new inode to sector SECTOR on the file system
   device.
   Returns true if successful.
   Returns false if memory or disk allocation fails. */
bool
inode_create (block_sector_t sector, off_t length)
{
  struct inode_disk *disk_inode = NULL;
  bool success = false;

  ASSERT (length >= 0);

  /* If this assertion fails, the inode structure is not exactly
     one sector in size, and you should fix that. */
  ASSERT (sizeof *disk_inode == BLOCK_SECTOR_SIZE);

  disk_inode = calloc (1, sizeof *disk_inode);
  if (disk_inode != NULL)
    {
      size_t sectors = bytes_to_sectors (length);
      disk_inode->length = length;
      disk_inode->magic = INODE_MAGIC;
      disk_inode->depth = 25;

//      printf("创建文件长度为%d",length);
//      printf("需要的扇区数为%d\n",sectors);

      //ht
      //把inode所有扇区号赋值为0
      //初始化
      int k;
      for(k = 0;k < DIRECT_CNT;k++)
      {
          disk_inode->direct[k]=0;
      }
      disk_inode->indirect1=0;
      disk_inode->indirect2=0;

      //分情况申请扇区
      if(sectors > 0)
      {
           static char zeros[BLOCK_SECTOR_SIZE];
           size_t i;
           for(i = 0;i < sectors;i++)
           {
               //直接区申请
               if(i < DIRECT_CNT)
               {
                   if(!add_direct(disk_inode,zeros))
                   {
                       printf("出错A\n");
                       printf("此时循环到的扇区数为%d\n",i);
                       free(disk_inode);
                       return success;
                   }
               }//一级间接区申请
               else if(i >=DIRECT_CNT && i < DOUBLE_INDIRECT_CNT)
               {
                   if(!add_indirect1(disk_inode,zeros))
                   {
                       printf("出错B\n");
                       printf("此时循环到的扇区数为%d\n",i);
                       free(disk_inode);
                       return success;
                   }
               }//二级间接区申请
               else
               {
                   if(!add_indirect2(disk_inode,zeros))
                   {
                       printf("出错C\n");
                       printf("此时循环到的扇区数为%d\n",i);
                       free(disk_inode);
                       return success;
                   }
               }
           }

      }

      //把inode写回扇区
      write_to_cache(fs_device,sector,0,BLOCK_SECTOR_SIZE,disk_inode);
      success = true;


//      printf("创建了inode该inode占用了扇区%d\n",sector);
//      printf("申请长度为%d\n",length);
//      printf("申请直接1为%d\n",disk_inode->direct[0]);
//      printf("申请直接2为%d\n",disk_inode->direct[1]);
//      printf("申请间接1级为%d\n",disk_inode->indirect1);
//      printf("申请间接2级为%d\n",disk_inode->indirect2);
//      printf("--------------------------------------\n");
      free(disk_inode);
  }



//      if (free_map_allocate (sectors, &disk_inode->start))
//        {
//          //[zyh]
//          write_to_cache(fs_device,sector,disk_inode);
//          //block_write (fs_device, sector, disk_inode);
//          if (sectors > 0)
//            {
//              static char zeros[BLOCK_SECTOR_SIZE];
//              size_t i;
              
//              for (i = 0; i < sectors; i++){
//                  //[zyh]
//                  write_to_cache(fs_device,disk_inode->start + i,zeros);
//                //block_write (fs_device, disk_inode->start + i, zeros);
//              }
//            }
//          success = true;
//        }
//          free (disk_inode);
//    }

  return success;
}

/* Reads an inode from SECTOR
   and returns a `struct inode' that contains it.
   Returns a null pointer if memory allocation fails. */
struct inode *
inode_open (block_sector_t sector)
{
  struct list_elem *e;
  struct inode *inode;

  /* Check whether this inode is already open. */
  for (e = list_begin (&open_inodes); e != list_end (&open_inodes);
       e = list_next (e)) 
    {
      inode = list_entry (e, struct inode, elem);
      if (inode->sector == sector) 
        {
          inode_reopen (inode);
          return inode; 
        }
    }

  /* Allocate memory. */
  inode = malloc (sizeof *inode);
  if (inode == NULL)
    return NULL;

  /* Initialize. */
  list_push_front (&open_inodes, &inode->elem);
  inode->sector = sector;
  inode->open_cnt = 1;
  inode->deny_write_cnt = 0;
  inode->removed = false;
  //[zyh]
  read_from_cache(fs_device,inode->sector,0,BLOCK_SECTOR_SIZE,&inode->data);

  //block_read (fs_device, inode->sector, &inode->data);

//  printf("打开了扇区%d的inode\n",sector);
//  printf("该扇区inode申请的长度为为%d\n",inode->data.length);
//  printf("申请直接1为%d\n",inode->data.direct[0]);
//  printf("申请直接2为%d\n",inode->data.direct[1]);
//  printf("--------------------------------------\n");

  return inode;
}

/* Reopens and returns INODE. */
struct inode *
inode_reopen (struct inode *inode)
{
  if (inode != NULL)
    inode->open_cnt++;
  return inode;
}

/* Returns INODE's inode number. */
block_sector_t
inode_get_inumber (const struct inode *inode)
{
  return inode->sector;
}

/* Closes INODE and writes it to disk.
   If this was the last reference to INODE, frees its memory.
   If INODE was also a removed inode, frees its blocks. */
void
inode_close (struct inode *inode) 
{
  /* Ignore null pointer. */
  if (inode == NULL)
    return;

  /* Release resources if this was the last opener. */
  if (--inode->open_cnt == 0)
    {
      /* Remove from inode list and release lock. */
      list_remove (&inode->elem);
 
      /* Deallocate blocks if removed. */
      if (inode->removed) 
        {
          //释放主索引块
          free_map_release (inode->sector, 1);
//          free_map_release (inode->data.start,
//                            bytes_to_sectors (inode->data.length));
//        }

          //ht
          //释放所有扇区
         release_direct(&inode->data);
         release_indirect1(&inode->data);
         release_indirect2(&inode->data);
      }



      free (inode); 
    }
}

/* Marks INODE to be deleted when it is closed by the last caller who
   has it open. */
void
inode_remove (struct inode *inode) 
{
  ASSERT (inode != NULL);
  inode->removed = true;
}

/* Reads SIZE bytes from INODE into BUFFER, starting at position OFFSET.
   Returns the number of bytes actually read, which may be less
   than SIZE if an error occurs or end of file is reached. */
off_t
inode_read_at (struct inode *inode, void *buffer_, off_t size, off_t offset) 
{
  uint8_t *buffer = buffer_;
  off_t bytes_read = 0;
  //uint8_t *bounce = NULL;

//  if(inode->sector == 174)
//  {
//      printf("读取了%d扇区的inode\n",inode->sector);
//      printf("申请长度为%d\n",inode->data.length);
//      printf("申请直接1为%d\n",inode->data.direct[0]);
//      printf("申请直接2为%d\n",inode->data.direct[1]);
//      printf("offse是%d,size是%d\n",offset,size);
//  }

  while (size > 0) 
    {

      /* Disk sector to read, starting byte offset within sector. */
//      block_sector_t sector_idx = byte_to_sector (inode, offset);
      block_sector_t sector_idx = byte_to_sector_index (inode, offset);

      int sector_ofs = offset % BLOCK_SECTOR_SIZE;

/*      printf("通过offset为%d找到的扇区号为%d\n",offset,sector_idx);
      printf("同时size是%d\n",size);
      printf("--------------------------------------\n");*/



      /* Bytes left in inode, bytes left in sector, lesser of the two. */
      off_t inode_left = inode_length (inode) - offset;
      int sector_left = BLOCK_SECTOR_SIZE - sector_ofs;
      int min_left = inode_left < sector_left ? inode_left : sector_left;

      /* Number of bytes to actually copy out of this sector. */
      int chunk_size = size < min_left ? size : min_left;
      if (chunk_size <= 0)
        break;
      //[zyh]
      read_from_cache (fs_device, sector_idx, sector_ofs,chunk_size,buffer + bytes_read);

      /*if (sector_ofs == 0 && chunk_size == BLOCK_SECTOR_SIZE)
        {
           Read full sector directly into caller's buffer.
          //block_read (fs_device, sector_idx, buffer + bytes_read);
    	  //[zyh]
    	  read_from_cache (fs_device, sector_idx, buffer + bytes_read);
        }
      else 
        {
           Read sector into bounce buffer, then partially copy
             into caller's buffer.
          if (bounce == NULL) 
            {
              bounce = malloc (BLOCK_SECTOR_SIZE);
              if (bounce == NULL)
                break;
            }
          //block_read (fs_device, sector_idx, bounce);
          //[zyh]
          read_from_cache (fs_device, sector_idx, bounce);

          memcpy (buffer + bytes_read, bounce + sector_ofs, chunk_size);
        }*/
      
      /* Advance. */
      size -= chunk_size;
      offset += chunk_size;
      bytes_read += chunk_size;
    }
  //free (bounce);

  return bytes_read;
}

/* Writes SIZE bytes from BUFFER into INODE, starting at OFFSET.
   Returns the number of bytes actually written, which may be
   less than SIZE if end of file is reached or an error occurs.
   (Normally a write at end of file would extend the inode, but
   growth is not yet implemented.) */
off_t
inode_write_at (struct inode *inode, const void *buffer_, off_t size,
                off_t offset) 
{
    //printf("%s\n",(char *)buffer_);
  const uint8_t *buffer = buffer_;
  off_t bytes_written = 0;
  //uint8_t *bounce = NULL;

  if (inode->deny_write_cnt)
    return 0;

//  if(offset > inode->data.length)
//  {
//      PANIC("位移超过文件长度.");
//  }


  //ht
  //实现文件增长
  //当文件长度不够时，循环添加文件的长度，并且根据需要申请新的扇区
  //循环直到文件长度满足要求
  if((offset + size) > inode->data.length)
  {  
      static char zeros[BLOCK_SECTOR_SIZE];
      while((offset + size) > inode->data.length)
      {
          size_t old_sectors = bytes_to_sectors(inode->data.length);
          size_t new_sectors = bytes_to_sectors(offset+size);

          //不需要申请扇区
          if(old_sectors == new_sectors)
          {
              size_t chunk = (offset+size) - (inode->data.length);

              inode->data.length+=chunk;
              write_to_cache(fs_device,inode->sector,0,BLOCK_SECTOR_SIZE,&inode->data);
          }//需要申请扇区，分情况申请
          else
          {
              //直接区申请
              if(inode->data.length <= 4608)
              {
//                  if(inode->sector == 174)
//                  {
//                      static int i = 0;
//                      printf("添加%d号直接\n",i);
//                  }



                  if(!add_direct(&inode->data,zeros))
                  {
                      printf("此时文件长度为%d\n",inode->data.length);
                      printf("该inode直接1为%d\n",inode->data.direct[0]);
                      printf("该inode直接2为%d\n",inode->data.direct[1]);
                      printf("出错时offset是%d，size是%d\n",offset,size);
                      PANIC("直接出错\n");
                  }
              }//一级间接区申请
              else if(inode->data.length > 4608 && inode->data.length <= 70144)
              {
//                  if(inode->sector == 174)
//                  {
//                      static int j = 0;
//                      printf("添加%d号间接1\n",j);
//                  }

                  if(!add_indirect1(&inode->data,zeros))
                  {
                      PANIC("间接1出错\n");
                  }
              }//二级间接区申请
              else
              {
//                  if(inode->sector == 174)
//                  {
//                      static int j = 0;
//                      printf("添加%d号间接2\n",j);
//                  }

                  if(!add_indirect2(&inode->data,zeros))
                  {
                      PANIC("间接2出错\n");
                  }
              }

              size_t chunk = (offset+size) - (inode->data.length);

              //在增加文件长度时如果超过一个扇区则要全加上
              //如果不足一个扇区，则要加上实际的部分
              if(chunk < BLOCK_SECTOR_SIZE)
              {
                  inode->data.length+=chunk;
              }
              else
              {
                  inode->data.length+=BLOCK_SECTOR_SIZE;
              }
              write_to_cache(fs_device,inode->sector,0,BLOCK_SECTOR_SIZE,&inode->data);
//              printf("此时文件长度为%d\n",inode->data.length);
          }

      }

//      printf("出循环时文件长度为%d\n",inode->data.length);
//      PANIC("写入字节超过文件长度.");
  }


  while (size > 0)
    {

/*      printf("写了%d扇区的inode\n",inode->sector);
      printf("申请长度为%d\n",inode->data.length);
      printf("申请直接1为%d\n",inode->data.direct[0]);
      printf("申请直接2为%d\n",inode->data.direct[1]);*/

      /* Sector to write, starting byte offset within sector. */
//      block_sector_t sector_idx = byte_to_sector (inode, offset);
      block_sector_t sector_idx = byte_to_sector_index (inode, offset);
      int sector_ofs = offset % BLOCK_SECTOR_SIZE;

/*      printf("通过offset为%d找到的扇区号为%d\n",offset,sector_idx);
      printf("同时size是%d\n",size);
      printf("--------------------------------------\n");*/

      /* Bytes left in inode, bytes left in sector, lesser of the two. */
      off_t inode_left = inode_length (inode) - offset;
      int sector_left = BLOCK_SECTOR_SIZE - sector_ofs;
      int min_left = inode_left < sector_left ? inode_left : sector_left;

      /* Number of bytes to actually write into this sector. */
      int chunk_size = size < min_left ? size : min_left;
      if (chunk_size <= 0)
        break;

      write_to_cache(fs_device,sector_idx,sector_ofs,chunk_size,(void *)(buffer + bytes_written));
      /*if (sector_ofs == 0 && chunk_size == BLOCK_SECTOR_SIZE)
        {
           Write full sector directly to disk.
          //block_write (fs_device, sector_idx, buffer + bytes_written);
    	  //[zyh]
    	  write_to_cache(fs_device,sector_idx,0,BLOCK_SECTOR_SIZE,buffer + bytes_written);
        }
      else 
        {
           We need a bounce buffer.
          if (bounce == NULL) 
            {
              bounce = malloc (BLOCK_SECTOR_SIZE);
              if (bounce == NULL)
                break;
            }

           If the sector contains data before or after the chunk
             we're writing, then we need to read in the sector
             first.  Otherwise we start with a sector of all zeros.
          if (sector_ofs > 0 || chunk_size < sector_left) {
            //block_read (fs_device, sector_idx, bounce);
        	  //[zyh]
        	  read_from_cache(fs_device,sector_idx,bounce);
          }
          else
            memset (bounce, 0, BLOCK_SECTOR_SIZE);
          memcpy (bounce + sector_ofs, buffer + bytes_written, chunk_size);
          //block_write (fs_device, sector_idx, bounce);
    	  //[zyh]
    	  write_to_cache(fs_device,sector_idx,bounce);
        }*/

      /* Advance. */
      size -= chunk_size;
      offset += chunk_size;
      bytes_written += chunk_size;
    }

  //free (bounce);

  return bytes_written;
}

/* Disables writes to INODE.
   May be called at most once per inode opener. */
void
inode_deny_write (struct inode *inode) 
{
  inode->deny_write_cnt++;
  ASSERT (inode->deny_write_cnt <= inode->open_cnt);
}

/* Re-enables writes to INODE.
   Must be called once by each inode opener who has called
   inode_deny_write() on the inode, before closing the inode. */
void
inode_allow_write (struct inode *inode) 
{
  ASSERT (inode->deny_write_cnt > 0);
  ASSERT (inode->deny_write_cnt <= inode->open_cnt);
  inode->deny_write_cnt--;
}

/* Returns the length, in bytes, of INODE's data. */
off_t
inode_length (const struct inode *inode)
{
  return inode->data.length;
}

//ht
//在直接区申请扇区
bool
add_direct(struct inode_disk *disk_inode,void *buffer)
{
    int i;
    for(i = 0;i < DIRECT_CNT;i++)
    {
        if(disk_inode->direct[i] == 0)
            break;
    }
    if(i == DIRECT_CNT)
    {
        printf("Q\n");
        return false;
    }

    if(free_map_allocate(1,&disk_inode->direct[i]))
    {
        write_to_cache(fs_device,disk_inode->direct[i],0,BLOCK_SECTOR_SIZE,buffer);
        return true;
    }
    else
    {
        printf("W\n");
        return false;
    }
}

//直接区是否满
bool
is_direct_full(struct inode_disk *disk_inode)
{
    if(disk_inode->direct[DIRECT_CNT - 1]!=0)
        return true;
    else
        return false;
}

//在一级间接区申请扇区
bool
add_indirect1(struct inode_disk *disk_inode,void *buffer)
{
    if(disk_inode->indirect1 == 0)
    {
        if(free_map_allocate(1,&disk_inode->indirect1))
        {
            struct inode_indirect *fst = calloc(1,sizeof *fst);
            int i;
            for(i = 0;i < 128;i++)
            {
                fst->entry[i]=0;
            }
            write_to_cache(fs_device,disk_inode->indirect1,0,BLOCK_SECTOR_SIZE,fst);
            free(fst);
        }
        else
        {
//            printf("D\n");
            return false;
        }
    }

     struct inode_indirect *fst = calloc(1,sizeof *fst);
     read_from_cache(fs_device,disk_inode->indirect1,0,BLOCK_SECTOR_SIZE,fst);
     int i;
     for(i = 0;i < 128;i++)
     {
         if(fst->entry[i] == 0)
             break;
     }
     if(i == 128)
     {
//         printf("E\n");
         free(fst);
         return false;
     }
     if(free_map_allocate(1,&fst->entry[i]))
     {
         write_to_cache(fs_device,fst->entry[i],0,BLOCK_SECTOR_SIZE,buffer);
         write_to_cache(fs_device,disk_inode->indirect1,0,BLOCK_SECTOR_SIZE,fst);
         free(fst);
         return true;
     }
     else
     {
         return false;
     }
}

//一级间接区是否满
bool
is_indirect1_full(struct inode_disk *disk_inode)
{
    struct inode_indirect *fst = calloc(1,sizeof *fst);
    read_from_cache(fs_device,disk_inode->indirect1,0,BLOCK_SECTOR_SIZE,fst);
    bool flag;
    if(fst->entry[127] != 0)
        flag=true;
    else
        flag=false;
    free(fst);
    return flag;
}

//在二级间接区申请扇区
bool
add_indirect2(struct inode_disk *disk_inode,void *buffer)
{
    if(disk_inode->indirect2 == 0)
    {
        if(free_map_allocate(1,&disk_inode->indirect2))
        {
            struct inode_indirect *fst = calloc(1,sizeof *fst);
            int i;
            for(i = 0;i < 128;i++)
            {
                fst->entry[i]=0;
            }
            write_to_cache(fs_device,disk_inode->indirect2,0,BLOCK_SECTOR_SIZE,fst);
            free(fst);
        }
        else
        {
            printf("D\n");
            return false;
        }
    }

    struct inode_indirect *fst = calloc(1,sizeof *fst);
    read_from_cache(fs_device,disk_inode->indirect2,0,BLOCK_SECTOR_SIZE,fst);
    int k;
    for(k = 0;k < 128;k++)
    {
//        printf("k是%d\n",k);
        if(fst->entry[k] == 0)
        {
//            printf("---------------------------------------------------------------\n");
            if(free_map_allocate(1,&fst->entry[k]))
            {
//                printf("%d\n",fst->entry[k]);
                struct inode_indirect *scd = calloc(1,sizeof *scd);
                int i;
                for(i = 0;i < 128;i++)
                {
                    scd->entry[i]=0;
                }
                write_to_cache(fs_device,fst->entry[k],0,BLOCK_SECTOR_SIZE,scd);
                free(scd);
                k--;
            }
            else
            {
                printf("E\n");
                free(fst);
                return false;
            }
        }
        else
        {
//            printf("************************************\n");
            struct inode_indirect *scd = calloc(1,sizeof *scd);
            read_from_cache(fs_device,fst->entry[k],0,BLOCK_SECTOR_SIZE,scd);

            if(scd->entry[127]==0)
            {
                int i;
                for(i = 0;i< 128;i++)
                {
                    if(scd->entry[i] == 0)
                        break;
                }
                if(i == 128)
                {
                    printf("F\n");
                    free(scd);
                    free(fst);
                    return false;
                }
                if(free_map_allocate(1,&scd->entry[i]))
                {
                    write_to_cache(fs_device,scd->entry[i],0,BLOCK_SECTOR_SIZE,buffer);
                    write_to_cache(fs_device,fst->entry[k],0,BLOCK_SECTOR_SIZE,scd);
                    write_to_cache(fs_device,disk_inode->indirect2,0,BLOCK_SECTOR_SIZE,fst);
                    free(scd);
                    free(fst);
                    return true;
                }
                else
                {
                    printf("G\n");
                    free(scd);
                    free(fst);
                    return false;
                }
            }
            else
            {
                free(scd);
            }
        }
    }
    if(k == 128)
    {
        printf("H\n");
        free(fst);
        return false;
    }

    printf("I\n");
    return false;
}

//释放扇区
//以下三个函数都是
void
release_direct(struct inode_disk *disk_inode)
{
    int i;
    for(i = 0; i < DIRECT_CNT;i++)
    {
        if(disk_inode->direct[i]!=0)
        {
            free_map_release(disk_inode->direct[i],1);
        }
    }
}

void
release_indirect1(struct inode_disk *disk_inode)
{
    if(disk_inode->indirect1 !=0)
    {
        struct inode_indirect *fst = calloc(1,sizeof *fst);
        read_from_cache(fs_device,disk_inode->indirect1,0,BLOCK_SECTOR_SIZE,fst);
        int i;
        for(i = 0;i < 128;i++)
        {
            if(fst->entry[i]!=0)
            {
                free_map_release(fst->entry[i],1);
            }
        }
        free(fst);
    }
}

void
release_indirect2(struct inode_disk *disk_inode)
{
    if(disk_inode->indirect2 !=0)
    {
        struct inode_indirect *fst = calloc(1,sizeof *fst);
        read_from_cache(fs_device,disk_inode->indirect2,0,BLOCK_SECTOR_SIZE,fst);

        int k;
        for(k = 0;k < 128;k++)
        {
            if(fst->entry[k]!=0)
            {
                struct inode_indirect *scd = calloc(1,sizeof *scd);
                read_from_cache(fs_device,fst->entry[k],0,BLOCK_SECTOR_SIZE,scd);

                int i;
                for(i = 0;i < 128;i++)
                {
                    if(scd->entry[i]!=0)
                    {
                        free_map_release(scd->entry[i],1);
                    }
                }
                free(scd);
            }
            free(fst);
        }
    }
}

//检测该inode是否可以即是否被删除
bool inode_availabe(const struct inode *ind)
{
    return !ind->removed;
}

//无用
uint32_t
get_depth(struct inode *ind)
{
    return ind->data.depth;
}

//无用
void
set_depth(block_sector_t sector, uint32_t dep)
{
    struct inode_disk *disk_inode = calloc(1,sizeof *disk_inode);
    read_from_cache(fs_device,sector,0,BLOCK_SECTOR_SIZE,disk_inode);
    disk_inode->depth = dep;
    write_to_cache(fs_device,sector,0,BLOCK_SECTOR_SIZE,disk_inode);
    free(disk_inode);
}
